package com.ctec.dataprocess.json;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ctec.asset.AssetPassword;
import com.ctec.asset.AssetSuspectedData;
import com.ctec.service.AssetPasswordService;
import com.ctec.service.AssetSuspectedDataService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RequestMapping("json")
@RestController
@Slf4j
public class ProcessJson {

    /**
     * 接口测试txt数据解析入库
     */

    @Resource
    private AssetSuspectedDataService assetSuspectedDataService;

    @RequestMapping("process")
    public String process(@RequestParam String path) {

        // 提取前100行数据
        StringBuilder stringBuilder = new StringBuilder();
        int count = 100;

        try {
            // 创建一个FileReader对象，用于读取文件
            FileReader fileReader = new FileReader(path);
            // 创建一个BufferedReader对象，用于缓冲读取文件内容
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            // 逐行读取文件内容，直到读取到文件末尾（readLine()返回null）
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                if (count-- > 0) {
                    System.out.println(line);
                    JSONObject jsonObject = JSON.parseObject(line);
// 定义属性名映射关系
                    // 创建配置对象，设置别名映射关系
                    JSONReader.Feature[] features = new JSONReader.Feature[]{
                            JSONReader.Feature.FieldBased
                     };

                    AssetSuspectedData assetSuspectedData = JSON.parseObject(jsonObject.getString("_source"), AssetSuspectedData.class, features);
                    assetSuspectedDataService.save(assetSuspectedData);


                } else {
                    break;
                }
            }

            // 关闭BufferedReader和FileReader，释放资源
            bufferedReader.close();
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "结束";
    }


}
